/
PortalSecurity.cs
1064 lines (942 loc) · 49 KB
/
PortalSecurity.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Security
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using DotNetNuke.Common;
using DotNetNuke.Common.Lists;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Entities.Users.Social;
using DotNetNuke.Internal.SourceGenerators;
using DotNetNuke.Security.Cookies;
using DotNetNuke.Services.Cryptography;
public class PortalSecurity
{
public static readonly PortalSecurity Instance = new PortalSecurity();
private const string RoleFriendPrefix = "FRIEND:";
private const string RoleFollowerPrefix = "FOLLOWER:";
private const string RoleOwnerPrefix = "OWNER:";
private const string BadStatementExpression = ";|--|\bcreate\b|\bdrop\b|\bselect\b|\binsert\b|\bdelete\b|\bupdate\b|\bunion\b|sp_|xp_|\bexec\b|\bexecute\b|/\\*.*\\*/|\bdeclare\b|\bwaitfor\b|%|&";
private const RegexOptions RxOptions = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled;
private static readonly DateTime OldExpiryTime = new DateTime(1999, 1, 1);
private static readonly Regex StripTagsRegex = new Regex("<[^<>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex BadStatementRegex = new Regex(BadStatementExpression, RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex ControlCharactersRegex = new Regex(@"\p{C}+", RegexOptions.Compiled);
private static readonly Regex ControlCharacterToWhitespaceRegex = new Regex(@"\r\n|\r|\n|\t", RegexOptions.Compiled);
private static readonly Regex[] RxListStrings = new[]
{
new Regex("<script[^>]*>.*?</script[^><]*>", RxOptions),
new Regex("<script", RxOptions),
new Regex("<input[^>]*>.*?</input[^><]*>", RxOptions),
new Regex("<object[^>]*>.*?</object[^><]*>", RxOptions),
new Regex("<embed[^>]*>.*?</embed[^><]*>", RxOptions),
new Regex("<applet[^>]*>.*?</applet[^><]*>", RxOptions),
new Regex("<form[^>]*>.*?</form[^><]*>", RxOptions),
new Regex("<option[^>]*>.*?</option[^><]*>", RxOptions),
new Regex("<select[^>]*>.*?</select[^><]*>", RxOptions),
new Regex("<source[^>]*>.*?</source[^><]*>", RxOptions),
new Regex("<iframe[^>]*>.*?</iframe[^><]*>", RxOptions),
new Regex("<iframe.*?<", RxOptions),
new Regex("<iframe.*?", RxOptions),
new Regex("<ilayer[^>]*>.*?</ilayer[^><]*>", RxOptions),
new Regex("<form[^>]*>", RxOptions),
new Regex("</form[^><]*>", RxOptions),
new Regex("\bonerror\b", RxOptions),
new Regex("\bonload\b", RxOptions),
new Regex("\bonfocus\b", RxOptions),
new Regex("\bonblur\b", RxOptions),
new Regex("\bonclick\b", RxOptions),
new Regex("\bondblclick\b", RxOptions),
new Regex("\bonchange\b", RxOptions),
new Regex("\bonselect\b", RxOptions),
new Regex("\bonsubmit\b", RxOptions),
new Regex("\bonreset\b", RxOptions),
new Regex("\bonkeydown\b", RxOptions),
new Regex("\bonkeyup\b", RxOptions),
new Regex("\bonkeypress\b", RxOptions),
new Regex("\bonmousedown\b", RxOptions),
new Regex("\bonmousemove\b", RxOptions),
new Regex("\bonmouseout\b", RxOptions),
new Regex("\bonmouseover\b", RxOptions),
new Regex("\bonmouseup\b", RxOptions),
new Regex("\bonreadystatechange\b", RxOptions),
new Regex("\bonfinish\b", RxOptions),
new Regex("javascript:", RxOptions),
new Regex("vbscript:", RxOptions),
new Regex("unescape", RxOptions),
new Regex("alert[\\s( )]*\\([\\s( )]*'?[\\s( )]*[\"(")]?", RxOptions),
new Regex(@"eval*.\(", RxOptions),
};
private static readonly Regex DangerElementsRegex = new Regex(@"(<[^>]*?) on.*?\=(['""]*)[\s\S]*?(\2)( *)([^>]*?>)", RxOptions);
private static readonly Regex DangerElementContentRegex = new Regex(@"on.*?\=(['""]*)[\s\S]*?(\1)( *)", RxOptions);
/// <summary>
/// The FilterFlag enum determines which filters are applied by the InputFilter
/// function. The Flags attribute allows the user to include multiple
/// enumerated values in a single variable by OR'ing the individual values
/// together.
/// </summary>
[Flags]
public enum FilterFlag
{
MultiLine = 1,
[Obsolete("Deprecated in DotNetNuke 9.8.1. A direct call to WebUtility.HtmlEncode should be used. Scheduled for removal in v11.0.0.")]
NoMarkup = 2,
[Obsolete("Deprecated in DotNetNuke 9.8.1. A direct call to WebUtility.HtmlEncode should be used. Scheduled for removal in v11.0.0.")]
NoScripting = 4,
[Obsolete("Deprecated in DotNetNuke 9.8.1. Parameterized SQL should be preferred for SQL Injection protection. Scheduled for removal in v11.0.0.")]
NoSQL = 8,
[Obsolete("Deprecated in DotNetNuke 9.8.1. Individual string replacement should be completed. Scheduled for removal in v11.0.0.")]
NoAngleBrackets = 16,
NoProfanity = 32,
/// <summary>
/// Removes all unicode control characters (like \0, \t, \n, \r, etc.) from the string.
/// </summary>
/// <remarks>
/// The control characters \r\n, \r, \n, and \t are replaced with a single space instead of being removed.
/// </remarks>
NoControlCharacters = 64,
}
/// <summary>Determines the configuration source for the remove and replace functions.</summary>
public enum ConfigType
{
ListController = 0,
ExternalFile = 1,
}
/// <summary>
/// determines whether to use system (host) list, portal specific list, or combine both
/// At present only supported by ConfigType.ListController.
/// </summary>
public enum FilterScope
{
SystemList = 0,
PortalList = 1,
SystemAndPortalList = 2,
}
private enum RoleType
{
Security = 0,
Friend = 1,
Follower = 2,
Owner = 3,
}
/// <summary>
/// Forces the secure connection.
/// </summary>
public static void ForceSecureConnection()
{
// get current url
var url = HttpContext.Current.Request.Url.ToString();
// if unsecure connection
if (url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase))
{
// switch to secure connection
url = "https://" + url.Substring("http://".Length);
// append ssl parameter to querystring to indicate secure connection processing has already occurred
if (url.IndexOf("?", StringComparison.Ordinal) == -1)
{
url = url + "?ssl=1";
}
else
{
url = url + "&ssl=1";
}
// redirect to secure connection
HttpContext.Current.Response.Redirect(url, true);
}
}
/// <summary>
/// Gets the cookie domain for the portal group or from web.config.
/// </summary>
/// <param name="portalId">The portal identifier.</param>
/// <returns>Cookie domain for the portal group or from web.config.</returns>
public static string GetCookieDomain(int portalId)
{
string cookieDomain = string.Empty;
if (PortalController.IsMemberOfPortalGroup(portalId))
{
// set cookie domain for portal group
var groupController = new PortalGroupController();
var group = groupController.GetPortalGroups().SingleOrDefault(p => p.MasterPortalId == PortalController.GetEffectivePortalId(portalId));
if (@group != null
&& !string.IsNullOrEmpty(@group.AuthenticationDomain)
&& PortalSettings.Current.PortalAlias.HTTPAlias.Contains(@group.AuthenticationDomain))
{
cookieDomain = @group.AuthenticationDomain;
}
if (string.IsNullOrEmpty(cookieDomain))
{
cookieDomain = FormsAuthentication.CookieDomain;
}
}
else
{
// set cookie domain to be consistent with domain specification in web.config
cookieDomain = FormsAuthentication.CookieDomain;
}
return cookieDomain;
}
/// <summary>
/// Determines whether the current user is denied for the given role(s).
/// </summary>
/// <param name="roles">The semicolon separated list of roles.</param>
/// <returns>
/// <c>true</c> if the current user is denied from the provided specified roles; otherwise, <c>false</c>.
/// </returns>
public static bool IsDenied(string roles)
{
UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo();
PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings();
return IsDenied(objUserInfo, settings, roles);
}
/// <summary>
/// Determines whether the specified user is denied for the given roles.
/// </summary>
/// <param name="objUserInfo">The user information.</param>
/// <param name="settings">The settings.</param>
/// <param name="roles">The semicolon separated list of roles.</param>
/// <returns>
/// <c>true</c> if the specified user is denied; otherwise, <c>false</c>.
/// </returns>
public static bool IsDenied(UserInfo objUserInfo, PortalSettings settings, string roles)
{
// super user always has full access
if (objUserInfo.IsSuperUser)
{
return false;
}
bool isDenied = false;
if (roles != null)
{
// permissions strings are encoded with Deny permissions at the beginning and Grant permissions at the end for optimal performance
foreach (string role in roles.Split(new[] { ';' }))
{
if (!string.IsNullOrEmpty(role))
{
// Deny permission
if (role.StartsWith("!"))
{
// Portal Admin cannot be denied from his/her portal (so ignore deny permissions if user is portal admin)
if (settings != null && !(settings.PortalId == objUserInfo.PortalID && objUserInfo.IsInRole(settings.AdministratorRoleName)))
{
string denyRole = role.Replace("!", string.Empty);
if (denyRole == Globals.glbRoleAllUsersName || objUserInfo.IsInRole(denyRole))
{
isDenied = true;
break;
}
}
}
}
}
}
return isDenied;
}
/// <summary>
/// Determines whether the current user belonds to the specified role.
/// </summary>
/// <param name="role">The role name.</param>
/// <returns>
/// <c>true</c> if user belongs to the specified role; otherwise, <c>false</c>.
/// </returns>
public static bool IsInRole(string role)
{
if (!string.IsNullOrEmpty(role) && role == Globals.glbRoleUnauthUserName && !HttpContext.Current.Request.IsAuthenticated)
{
return true;
}
return IsInRoles(UserController.Instance.GetCurrentUserInfo(), PortalController.Instance.GetCurrentPortalSettings(), role);
}
/// <summary>
/// Determines whether the current user belongs to the specified roles.
/// </summary>
/// <param name="roles">The semicolon separated list of roles.</param>
/// <returns>
/// <c>true</c> if user belongs to the specified roles; otherwise, <c>false</c>.
/// </returns>
public static bool IsInRoles(string roles)
{
UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo();
PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings();
return IsInRoles(objUserInfo, settings, roles);
}
/// <summary>
/// Determines whether the provided user belongs to the specified roles.
/// </summary>
/// <param name="objUserInfo">The user information.</param>
/// <param name="settings">The settings.</param>
/// <param name="roles">The semicolon separated list of roles.</param>
/// <returns>
/// <c>true</c> if the provided user belongs to the specific roles; otherwise, <c>false</c>.
/// </returns>
public static bool IsInRoles(UserInfo objUserInfo, PortalSettings settings, string roles)
{
// super user always has full access
bool isInRoles = objUserInfo.IsSuperUser;
if (!isInRoles)
{
if (roles != null)
{
foreach (string role in roles.Split(new[] { ';' }))
{
bool? roleAllowed;
ProcessRole(objUserInfo, settings, role, out roleAllowed);
if (roleAllowed.HasValue)
{
isInRoles = roleAllowed.Value;
break;
}
}
}
}
return isInRoles;
}
/// <summary>
/// Determines whether the specified user is a friend of the current user.
/// </summary>
/// <param name="userId">The user identifier.</param>
/// <returns>
/// <c>true</c> if the specified user is a friend of the current user; otherwise, <c>false</c>.
/// </returns>
public static bool IsFriend(int userId)
{
UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo();
PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings();
return IsInRoles(objUserInfo, settings, RoleFriendPrefix + userId);
}
/// <summary>
/// Determines whether the specified user is a follower of the current user.
/// </summary>
/// <param name="userId">The user identifier.</param>
/// <returns>
/// <c>true</c> if the specified user is a follower of the current user; otherwise, <c>false</c>.
/// </returns>
public static bool IsFollower(int userId)
{
UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo();
PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings();
return IsInRoles(objUserInfo, settings, RoleFollowerPrefix + userId);
}
/// <summary>
/// Determines whether the specified user is an owner.
/// </summary>
/// <param name="userId">The user identifier.</param>
/// <returns>
/// <c>true</c> if the specified user is an owner; otherwise, <c>false</c>.
/// </returns>
public static bool IsOwner(int userId)
{
UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo();
PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings();
return IsInRoles(objUserInfo, settings, RoleOwnerPrefix + userId);
}
/// <summary>This function creates a random key.</summary>
/// <param name="numBytes">This is the number of bytes for the key.</param>
/// <returns>A random string.</returns>
/// <remarks>This is a public function used for generating SHA1 keys.</remarks>
public string CreateKey(int numBytes)
{
using (var rng = new RNGCryptoServiceProvider())
{
var buff = new byte[numBytes];
rng.GetBytes(buff);
return BytesToHexString(buff);
}
}
/// <summary>
/// Decrypts the provided string data using a supplied key.
/// </summary>
/// <param name="strKey">The encryption key.</param>
/// <param name="strData">The encrypted data.</param>
/// <returns>The decrypted string.</returns>
public string Decrypt(string strKey, string strData)
{
return CryptographyProvider.Instance().DecryptParameter(strData, strKey);
}
/// <summary>
/// Decrypts a string using a provided passphrase.
/// </summary>
/// <param name="message">The encrypted message.</param>
/// <param name="passphrase">The passphrase.</param>
/// <returns>The decrypted string.</returns>
public string DecryptString(string message, string passphrase)
{
return CryptographyProvider.Instance().DecryptString(message, passphrase);
}
/// <summary>
/// Encrypts the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="data">The data.</param>
/// <returns>The encrypted string.</returns>
public string Encrypt(string key, string data)
{
return CryptographyProvider.Instance().EncryptParameter(data, key);
}
/// <summary>
/// Encrypts a string using a provided passphrase.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="passphrase">The passphrase.</param>
/// <returns>The encrypted string.</returns>
public string EncryptString(string message, string passphrase)
{
return CryptographyProvider.Instance().EncryptString(message, passphrase);
}
/// <summary>This function applies security filtering to the UserInput string.</summary>
/// <param name="userInput">This is the string to be filtered.</param>
/// <param name="filterType">Flags which designate the filters to be applied.</param>
/// <returns>Filtered UserInput.</returns>
public string InputFilter(string userInput, FilterFlag filterType)
{
if (userInput == null)
{
return string.Empty;
}
var tempInput = userInput;
if ((filterType & FilterFlag.NoAngleBrackets) == FilterFlag.NoAngleBrackets)
{
var removeAngleBrackets = Config.GetSetting("RemoveAngleBrackets") != null && bool.Parse(Config.GetSetting("RemoveAngleBrackets"));
if (removeAngleBrackets)
{
tempInput = FormatAngleBrackets(tempInput);
}
}
if ((filterType & FilterFlag.NoSQL) == FilterFlag.NoSQL)
{
tempInput = FormatRemoveSQL(tempInput);
}
if ((filterType & FilterFlag.NoMarkup) == FilterFlag.NoMarkup && IncludesMarkup(tempInput))
{
tempInput = HttpUtility.HtmlEncode(tempInput);
}
if ((filterType & FilterFlag.NoScripting) == FilterFlag.NoScripting)
{
tempInput = FilterStrings(tempInput);
}
if ((filterType & FilterFlag.MultiLine) == FilterFlag.MultiLine)
{
tempInput = FormatMultiLine(tempInput);
}
if ((filterType & FilterFlag.NoProfanity) == FilterFlag.NoProfanity)
{
tempInput = this.Replace(tempInput, ConfigType.ListController, "ProfanityFilter", FilterScope.SystemAndPortalList);
}
if ((filterType & FilterFlag.NoControlCharacters) == FilterFlag.NoControlCharacters)
{
tempInput = FormatRemoveControlCharacters(tempInput);
}
return tempInput;
}
/// <summary>Replaces profanity words with other words in the provided input string.</summary>
/// <remarks>
/// The correspondence between the words to search and the words to replace could be specified in two different places:
/// 1) In an external file. (NOT IMPLEMENTED)
/// 2) In System/Site lists.
/// The name of the System List is "ProfanityFilter". The name of the list in each portal is composed using the following rule:
/// "ProfanityFilter-" + PortalID.
/// </remarks>
/// <param name="inputString">The string to search the words in.</param>
/// <param name="configType">The type of configuration.</param>
/// <param name="configSource">The external file to search the words. Ignored when configType is ListController.</param>
/// <param name="filterScope">When using ListController configType, this parameter indicates which list(s) to use.</param>
/// <returns>The original text with the profanity words replaced.</returns>
public string Replace(string inputString, ConfigType configType, string configSource, FilterScope filterScope)
{
switch (configType)
{
case ConfigType.ListController:
const RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Singleline;
const string listName = "ProfanityFilter";
var listController = new ListController();
PortalSettings settings;
IEnumerable<ListEntryInfo> listEntryHostInfos;
IEnumerable<ListEntryInfo> listEntryPortalInfos;
switch (filterScope)
{
case FilterScope.SystemList:
listEntryHostInfos = listController.GetListEntryInfoItems(listName, string.Empty, Null.NullInteger);
inputString = listEntryHostInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", removeItem.Value, options));
break;
case FilterScope.SystemAndPortalList:
settings = PortalController.Instance.GetCurrentPortalSettings();
listEntryHostInfos = listController.GetListEntryInfoItems(listName, string.Empty, Null.NullInteger);
listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, string.Empty, settings.PortalId);
inputString = listEntryHostInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", removeItem.Value, options));
inputString = listEntryPortalInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", removeItem.Value, options));
break;
case FilterScope.PortalList:
settings = PortalController.Instance.GetCurrentPortalSettings();
listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, string.Empty, settings.PortalId);
inputString = listEntryPortalInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", removeItem.Value, options));
break;
}
break;
case ConfigType.ExternalFile:
throw new NotImplementedException();
default:
throw new ArgumentOutOfRangeException("configType");
}
return inputString;
}
/// <summary>Removes profanity words in the provided input string.</summary>
/// <remarks>
/// The words to search could be defined in two different places:
/// 1) In an external file. (NOT IMPLEMENTED)
/// 2) In System/Site lists.
/// The name of the System List is "ProfanityFilter". The name of the list in each portal is composed using the following rule:
/// "ProfanityFilter-" + PortalID.
/// </remarks>
/// <param name="inputString">The string to search the words in.</param>
/// <param name="configType">The type of configuration.</param>
/// <param name="configSource">The external file to search the words. Ignored when configType is ListController.</param>
/// <param name="filterScope">When using ListController configType, this parameter indicates which list(s) to use.</param>
/// <returns>The original text with the profanity words removed.</returns>
public string Remove(string inputString, ConfigType configType, string configSource, FilterScope filterScope)
{
switch (configType)
{
case ConfigType.ListController:
const RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Singleline;
const string listName = "ProfanityFilter";
var listController = new ListController();
PortalSettings settings;
IEnumerable<ListEntryInfo> listEntryHostInfos;
IEnumerable<ListEntryInfo> listEntryPortalInfos;
switch (filterScope)
{
case FilterScope.SystemList:
listEntryHostInfos = listController.GetListEntryInfoItems(listName, string.Empty, Null.NullInteger);
inputString = listEntryHostInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", string.Empty, options));
break;
case FilterScope.SystemAndPortalList:
settings = PortalController.Instance.GetCurrentPortalSettings();
listEntryHostInfos = listController.GetListEntryInfoItems(listName, string.Empty, Null.NullInteger);
listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, string.Empty, settings.PortalId);
inputString = listEntryHostInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", string.Empty, options));
inputString = listEntryPortalInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", string.Empty, options));
break;
case FilterScope.PortalList:
settings = PortalController.Instance.GetCurrentPortalSettings();
listEntryPortalInfos = listController.GetListEntryInfoItems(listName + "-" + settings.PortalId, string.Empty, settings.PortalId);
inputString = listEntryPortalInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", string.Empty, options));
break;
}
break;
case ConfigType.ExternalFile:
throw new NotImplementedException();
default:
throw new ArgumentOutOfRangeException("configType");
}
return inputString;
}
/// <summary>
/// Signs the provided user in and sets a persistent login cookie if needed.
/// </summary>
/// <param name="user">The user info.</param>
/// <param name="createPersistentCookie">if set to <c>true</c> [create persistent cookie].</param>
public void SignIn(UserInfo user, bool createPersistentCookie)
{
if (PortalController.IsMemberOfPortalGroup(user.PortalID) || createPersistentCookie)
{
// Create a custom auth cookie
// first, create the authentication ticket
var authenticationTicket = createPersistentCookie
? new FormsAuthenticationTicket(user.Username, true, Config.GetPersistentCookieTimeout())
: new FormsAuthenticationTicket(user.Username, false, Config.GetAuthCookieTimeout());
// encrypt it
var encryptedAuthTicket = FormsAuthentication.Encrypt(authenticationTicket);
// Create a new Cookie
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedAuthTicket)
{
Expires = authenticationTicket.Expiration,
Domain = GetCookieDomain(user.PortalID),
Path = FormsAuthentication.FormsCookiePath,
Secure = FormsAuthentication.RequireSSL,
};
if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null)
{
HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
}
HttpContext.Current.Response.Cookies.Set(authCookie);
AuthCookieController.Instance.Update(authCookie.Value, authCookie.Expires.ToUniversalTime(), user.UserID);
if (PortalController.IsMemberOfPortalGroup(user.PortalID))
{
var domain = GetCookieDomain(user.PortalID);
var siteGroupCookie = new HttpCookie("SiteGroup", domain)
{
Expires = authenticationTicket.Expiration,
Domain = domain,
Path = FormsAuthentication.FormsCookiePath,
Secure = FormsAuthentication.RequireSSL,
};
HttpContext.Current.Response.Cookies.Set(siteGroupCookie);
}
}
else
{
if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null)
{
HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
}
FormsAuthentication.SetAuthCookie(user.Username, false);
var authCookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName];
if (!string.IsNullOrEmpty(authCookie?.Value))
{
var t = FormsAuthentication.Decrypt(authCookie.Value);
if (t != null)
{
AuthCookieController.Instance.Update(authCookie.Value, t.Expiration.ToUniversalTime(), user.UserID);
}
}
}
if (user.IsSuperUser)
{
// save userinfo object in context to ensure Personalization is saved correctly
HttpContext.Current.Items["UserInfo"] = user;
}
// Identity the Login is processed by system.
HttpContext.Current.Items["DNN_UserSignIn"] = true;
}
/// <summary>
/// Signs the current user out.
/// </summary>
public void SignOut()
{
InvalidateAspNetSession(HttpContext.Current);
var currentAuthCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (currentAuthCookie != null)
{
// This will prevent next requests from being authenticated if using smae cookie
AuthCookieController.Instance.Update(currentAuthCookie.Value, OldExpiryTime, Null.NullInteger);
}
// Log User Off from Cookie Authentication System
var domainCookie = HttpContext.Current.Request.Cookies["SiteGroup"];
if (domainCookie == null)
{
// Forms Authentication's Logout
FormsAuthentication.SignOut();
}
else
{
// clear custom domain cookie
var domain = domainCookie.Value;
// Create a new Cookie
var str = string.Empty;
if (HttpContext.Current.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
{
str = "NoCookie";
}
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, str)
{
Expires = OldExpiryTime,
Domain = domain,
Path = FormsAuthentication.FormsCookiePath,
Secure = FormsAuthentication.RequireSSL,
};
HttpContext.Current.Response.Cookies.Set(authCookie);
var siteGroupCookie = new HttpCookie("SiteGroup", str)
{
Expires = OldExpiryTime,
Domain = domain,
Path = FormsAuthentication.FormsCookiePath,
Secure = FormsAuthentication.RequireSSL,
};
HttpContext.Current.Response.Cookies.Set(siteGroupCookie);
}
// Remove current userinfo from context items
HttpContext.Current.Items.Remove("UserInfo");
// remove language cookie
var httpCookie = HttpContext.Current.Response.Cookies["language"];
if (httpCookie != null)
{
httpCookie.Value = string.Empty;
}
// remove authentication type cookie
var cookie = HttpContext.Current.Response.Cookies["authentication"];
if (cookie != null)
{
cookie.Value = string.Empty;
}
// expire cookies
cookie = HttpContext.Current.Response.Cookies["portalaliasid"];
if (cookie != null)
{
cookie.Value = null;
cookie.Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/";
cookie.Expires = DateTime.Now.AddYears(-30);
}
cookie = HttpContext.Current.Response.Cookies["portalroles"];
if (cookie != null)
{
cookie.Value = null;
cookie.Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/";
cookie.Expires = DateTime.Now.AddYears(-30);
}
// clear any authentication provider tokens that match *UserToken convention e.g FacebookUserToken ,TwitterUserToken, LiveUserToken and GoogleUserToken
var authCookies = HttpContext.Current.Request.Cookies.AllKeys;
foreach (var authCookie in authCookies)
{
if (authCookie.EndsWith("UserToken"))
{
var auth = HttpContext.Current.Response.Cookies[authCookie];
if (auth != null)
{
auth.Value = null;
auth.Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/";
auth.Expires = DateTime.Now.AddYears(-30);
}
}
}
}
/// <summary>This function applies security filtering to the UserInput string, and reports whether the input string is valid.</summary>
/// <param name="userInput">This is the string to be filtered.</param>
/// <param name="filterType">Flags which designate the filters to be applied.</param>
/// <returns><see langword="true"/> if the input is valid, otherwise <see langword="false"/>.</returns>
public bool ValidateInput(string userInput, FilterFlag filterType)
{
string filteredInput = this.InputFilter(userInput, filterType);
return userInput == filteredInput;
}
/// <summary>
/// This function loops through every portal that has set its own AllowedExtensionWhitelist
/// and checks that there are no extensions there that are restricted by the host
///
/// The only time we should call this is if the host allowed extensions list has changed.
/// </summary>
/// <param name="newMasterList">Comma separated list of extensions that govern all users on this installation.</param>
public void CheckAllPortalFileExtensionWhitelists(string newMasterList)
{
var masterList = new FileExtensionWhitelist(newMasterList);
var portalSettings = Data.DataProvider.Instance().GetPortalSettingsBySetting("AllowedExtensionsWhitelist", null);
foreach (var portalId in portalSettings.Keys)
{
if (!string.IsNullOrEmpty(portalSettings[portalId]))
{
var portalExts = new FileExtensionWhitelist(portalSettings[portalId]);
var newValue = portalExts.RestrictBy(masterList).ToStorageString();
if (newValue != portalSettings[portalId])
{
PortalController.UpdatePortalSetting(portalId, "AllowedExtensionsWhitelist", newValue, false);
}
}
}
}
private static void ProcessRole(UserInfo user, PortalSettings settings, string roleName, out bool? roleAllowed)
{
var roleType = GetRoleType(roleName);
switch (roleType)
{
case RoleType.Friend:
ProcessFriendRole(user, roleName, out roleAllowed);
break;
case RoleType.Follower:
ProcessFollowerRole(user, roleName, out roleAllowed);
break;
case RoleType.Owner:
ProcessOwnerRole(user, roleName, out roleAllowed);
break;
default:
ProcessSecurityRole(user, settings, roleName, out roleAllowed);
break;
}
}
private static void ProcessFriendRole(UserInfo user, string roleName, out bool? roleAllowed)
{
roleAllowed = null;
var targetUser = UserController.Instance.GetUserById(user.PortalID, GetEntityFromRoleName(roleName));
var relationShip = RelationshipController.Instance.GetFriendRelationship(user, targetUser);
if (relationShip != null && relationShip.Status == RelationshipStatus.Accepted)
{
roleAllowed = true;
}
}
private static void ProcessFollowerRole(UserInfo user, string roleName, out bool? roleAllowed)
{
roleAllowed = null;
var targetUser = UserController.Instance.GetUserById(user.PortalID, GetEntityFromRoleName(roleName));
var relationShip = RelationshipController.Instance.GetFollowerRelationship(user, targetUser);
if (relationShip != null && relationShip.Status == RelationshipStatus.Accepted)
{
roleAllowed = true;
}
}
private static void ProcessOwnerRole(UserInfo user, string roleName, out bool? roleAllowed)
{
roleAllowed = null;
var entityId = GetEntityFromRoleName(roleName);
if (entityId == user.UserID)
{
roleAllowed = true;
}
}
private static int GetEntityFromRoleName(string roleName)
{
var roleParts = roleName.Split(':');
int result;
if (roleParts.Length > 1 && int.TryParse(roleParts[1], out result))
{
return result;
}
return Null.NullInteger;
}
private static void ProcessSecurityRole(UserInfo user, PortalSettings settings, string roleName, out bool? roleAllowed)
{
roleAllowed = null;
// permissions strings are encoded with Deny permissions at the beginning and Grant permissions at the end for optimal performance
if (!string.IsNullOrEmpty(roleName))
{
// Deny permission
if (roleName.StartsWith("!"))
{
// Portal Admin cannot be denied from his/her portal (so ignore deny permissions if user is portal admin)
if (settings != null && !(settings.PortalId == user.PortalID && user.IsInRole(settings.AdministratorRoleName)))
{
string denyRole = roleName.Replace("!", string.Empty);
if (denyRole == Globals.glbRoleAllUsersName || user.IsInRole(denyRole))
{
roleAllowed = false;
}
}
}
// Grant permission
else
{
if (roleName == Globals.glbRoleAllUsersName || user.IsInRole(roleName))
{
roleAllowed = true;
}
}
}
}
private static RoleType GetRoleType(string roleName)
{
if (roleName.StartsWith(RoleFriendPrefix, StringComparison.InvariantCultureIgnoreCase))
{
return RoleType.Friend;
}
if (roleName.StartsWith(RoleFollowerPrefix, StringComparison.InvariantCultureIgnoreCase))
{
return RoleType.Follower;
}
if (roleName.StartsWith(RoleOwnerPrefix, StringComparison.InvariantCultureIgnoreCase))
{
return RoleType.Owner;
}
return RoleType.Security;
}
private static string BytesToHexString(IEnumerable<byte> bytes)
{
var hexString = new StringBuilder();
foreach (var b in bytes)
{
hexString.Append(string.Format("{0:X2}", b));
}
return hexString.ToString();
}
/// <summary>
/// This function uses Regex search strings to remove HTML tags which are
/// targeted in Cross-site scripting (XSS) attacks. This function will evolve
/// to provide more robust checking as additional holes are found.
/// </summary>
/// <param name="strInput">This is the string to be filtered.</param>
/// <returns>Filtered UserInput.</returns>
/// <remarks>
/// This is a private function that is used internally by the <see cref="InputFilter"/> function.
/// </remarks>
private static string FilterStrings(string strInput)
{
// setup up list of search terms as items may be used twice
var tempInput = strInput;
if (string.IsNullOrWhiteSpace(tempInput))
{
return tempInput;
}
const string replacement = " ";
// remove the js event from html tags
var tagMatches = DangerElementsRegex.Matches(tempInput);
foreach (Match match in tagMatches)
{
var tagContent = match.Value;
var cleanTagContent = DangerElementContentRegex.Replace(tagContent, string.Empty);
tempInput = tempInput.Replace(tagContent, cleanTagContent);
}
// check if text contains encoded angle brackets, if it does it we decode it to check the plain text
if (tempInput.Contains(">") || tempInput.Contains("<") || tempInput.Contains("&#"))
{
// text is encoded, so decode and try again
tempInput = HttpUtility.HtmlDecode(tempInput);
tempInput = RxListStrings.Aggregate(tempInput, (current, s) => s.Replace(current, replacement));
// Re-encode
tempInput = HttpUtility.HtmlEncode(tempInput);
}
else
{
tempInput = RxListStrings.Aggregate(tempInput, (current, s) => s.Replace(current, replacement));
}